
/**
 * 操纵indexDB
 */

/**
 * 连接IndexDB
 * @param {数据库名} dbName 
 * @param {主表名} mainTableName 
 */
export const connectDB = (dbName, mainTableName) => {
  return new Promise((resolve, reject) => {
    let db = null;
    const request = window.indexedDB.open(dbName);
    request.onerror = function (event) {
      console.info('数据库连接报错', event);
      reject(event)
    }
    request.onsuccess = function (event) {
      db = event.target.result;
      console.info('数据库连接成功');
      resolve(db)
    }
    request.onupgradeneeded = function (event) {
      db = event.target.result;
      if (!db.objectStoreNames.contains(mainTableName)) {
        let objectStore = db.createObjectStore(mainTableName, { keyPath: 'name' });
        objectStore.createIndex('tags', 'tags', { unique: false });
        console.info('初始化主表成功');
      }
    }
  })
}

/**
 * 写入数据
 * @param {数据库实例} db 
 * @param {表名} tableName 
 * @param {键} name 
 * @param {值} tags 
 */
export const writeData = (db, tableName, name, tags) => {
  return new Promise((resolve, reject) => {
    readData(db, tableName, name).then((oldValue) => {
      const tb = db.transaction([tableName], 'readwrite').objectStore(tableName)
      if (oldValue) {
        const request = tb.put({
          name,
          tags
        })

        request.onsuccess = function (event) {
          console.log('数据写入成功');
          resolve(tags)
        };

        request.onerror = function (event) {
          console.log('数据写入失败');
        }

      } else {
        const request = tb.add({
          name,
          tags
        })

        request.onsuccess = function (event) {
          console.log('数据写入成功');
          resolve(tags)
        };

        request.onerror = function (event) {
          console.log('数据写入失败');
        }
      }
    })

  })
}

/**
 * 读取数据
 * @param {数据库实例} db 
 * @param {表名} tableName 
 * @param {键} name 
 */
export const readData = (db, tableName, name) => {
  return new Promise((resolve, reject) => {
    const request = db.transaction([tableName], 'readwrite')
      .objectStore(tableName)
      .get(name)

    request.onsuccess = function (event) {
      console.log('数据查询成功');
      resolve(request.result)
    };

    request.onerror = function (event) {
      console.log('数据查询失败');
    }
  })
}

/**
 * 读取表
 * @param {数据库实例} db 
 * @param {表名} tableName 
 */
export const readTableData = (db, tableName) => {
  return new Promise((resolve, reject) => {
    const request = db.transaction([tableName], 'readwrite')
      .objectStore(tableName)
      .getAll()

    request.onsuccess = function (event) {
      console.log('数据查询成功');
      resolve(request.result)
    };

    request.onerror = function (event) {
      console.log('数据查询失败');
    }
  })
}